package org.springframework.cloud.netflix.feign.ribbon;

import com.netflix.loadbalancer.IRule;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cloud.netflix.feign.FeignContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;

public class CanaryBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware, PriorityOrdered {
    private ApplicationContext context;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof IRule) // make canary routine possible
            return new CanaryCompositeRule((IRule) bean);
        else if (bean instanceof FeignContext) // expose RequestInterceptor to generate Feign.Builder to inherit headers
            ((FeignContext) bean).setApplicationContext(context);
        return bean;
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
}
